<?php
if(!defined('IN_WOGU')) {
    exit('Access Denied');
}

class Controller
{
    public $request = null;
    public $respones = null;
    protected $_view = null;

    public function init($request, $respones) {
        $this->request = $request;
        $this->respones = $respones;
        $this->_view = $this->getView();
        $this->_init();
    }

    public function dispatch() {
        $action = $this->request->get_action();
        if(!method_exists($this, $action)) {
            exit('the action ' . $action . ' not exist!');
        }

        $this->{$action}();
    }

    public function getView() {
        if(!$this->_view) {
            Loader::loadClass('View');
            $this->_view = new View($this->request);
            Register::set('View', $this->_view, 'WOGU_SYS');
        }

        return $this->_view;
    }

    public function forward($action, $controller = '', $module = '') {
        if('' != $module) {
            $this->request->set_module($module);
        }
        
        if('' != $controller) {
            $this->request->set_controller($controller);
        }
        
        $this->request->set_action($action);
        $this->request->setDispatched(false);
    }
    
    public function getUrl($action, $controller = '', $module = '', $params = array()) {
        if('' == $controller) {
            $controller = $this->request->controller;
        }
        
        if('' == $module) {
            $module = $this->request->module;
        }
        
        if(URL_REWRITE) {
            $url = SITE_DOMAIN . $module . '-' . $controller . '-' . $action;
            if(!empty($params)) {
                foreach($params as $k => $v) {
                    $url .= '-' . $k . '-' . $v;
                }
            }
            $url .= '.htm';
        } else {
            $url = SITE_DOMAIN . (isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']) . '?m=' . $module . '&c=' . $controller . '&a=' . $action;
            if(!empty($params)) {
                foreach($params as $k => $v) {
                    $url .= '&' . $k . '=' . $v;
                }
            }
        }
        
        return $url;
    }

    protected function _init() {}
}